<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Data;
use App\Category;
use App\Shape;
use App\Default_field;
use App\Custom_field;
use DB;
class dataController extends Controller
{
    static $tableName='data';
    /**
    * 软删除Trait
    */
    use \App\Http\utils\trashedMethods;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $keyWord=$request->input('keyWord');
        $is_trashed=$request->input('trashed');
        $category_id=$request->input('category_id');
        //动态查询条件
        $where=[];
        //查询分类下的数据
        if($keyWord){
            $where[]=["author","like","%".$keyWord."%"];
        }

        //查询分类下的数据
        if($category_id){
            $where[]=['category_id','=',$category_id];
        }

        if($is_trashed){
            $pageListData=Data::where($where)->onlyTrashed()->orderbyDesc('is_top')->orderbyDesc('sort')->orderByDesc('updated_at')->paginate(8);
        }else{
            $pageListData=Data::where($where)->orderbyDesc('is_top')->orderbyDesc('sort')->orderByDesc('updated_at')->paginate(8);
        }

        $selectData=Category::getTree(0,1);
        
        return view('admin.data.index',compact('pageListData','is_trashed','keyWord','selectData','category_id'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $category_id=$request->input('category_id');

        //当前分类
        $category=Category::select(['shape_id'])->find($category_id);

        //当前形状
        $shape=Shape::find($category->shape_id);

        $defaults=[];
        $customs=[];
        if($shape){
            //默认字段
            $default_ids=explode(',',$shape->default_ids);
            foreach ($default_ids as $item) {
                $defaults[]=Default_field::find($item);
            }
       
            //自定义字段
            $custom_ids=explode(',',$shape->custom_ids);
            foreach ($custom_ids as $item) {
                $customs[]=Custom_field::find($item);
            }
        }

        return view('admin.data.form',compact('category_id','defaults','customs'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        
        $schema=[
            'category_id'=>'required',
        ];
        $request->validate($schema);
        //所有参数
        $requestAll=$request->all();

 
        $createData=$request->only(['category_id','author','sort','is_top','is_recommend','is_release']);

        //创建
        $data=Data::create($createData);
                                                                            
        //默认字段
        $defaults=[];
        foreach ($requestAll as $key => $value) {
            if(strpos($key,'default_')!==false){
                $key=str_replace('default_','',$key);
                $defaults[]=[
                    'field_name'=>$key,
                    'field_value'=>$value,
                    'data_id'=>$data->id
                ];
            }
        }
        //批量插入默认字段值
        if($defaults){
            DB::table('default_values')->insert($defaults);
        }
        
        //自定义字段
        $customs=[];
        foreach ($requestAll as $key => $value) {
            if(strpos($key,'custom_')!==false){
                $key=str_replace('custom_','',$key);
                $customs[]=[
                    'field_name'=>$key,
                    'field_value'=>$value,
                    'data_id'=>$data->id
                ];
            }
        }
        //批量插入自定义字段值
        if($customs){
            DB::table('custom_values')->insert($customs);
        }

        return json(200,'创建成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //当前文章
        $editData=Data::find($id);

        $category_id=$editData->category_id;

        //当前分类
        $category=Category::select(['shape_id'])->find($category_id);

        //当前形状
        $shape=Shape::find($category->shape_id);
        //默认字段Key
        $defaults=[];
        //自定义字段Key
        $customs=[];
        //默认字段Value
        $defaults_values=[];
        //自定义字段Value
        $customs_values=[];
        if($shape){
            //默认字段
            $default_ids=explode(',',$shape->default_ids);
            foreach ($default_ids as $item) {
                $default_filed=Default_field::find($item);
                if($default_filed){
                    $defaults[]=$default_filed;
                    //获取默认字段的值
                    $values=DB::table('default_values')->where(['data_id'=>$id,'field_name'=>$default_filed->field_name])->first();
                    if($values){
                        $defaults_values[$values->field_name]=$values->field_value;
                    }
                }
            }
       
            //自定义字段
            $custom_ids=explode(',',$shape->custom_ids);
            foreach ($custom_ids as $item) {
                $custom_field=Custom_field::find($item);
                if($custom_field){
                    $customs[]=$custom_field;
                    //获取自定义字段的值 
                    $values=DB::table('custom_values')->where(['data_id'=>$id,'field_name'=>$custom_field->field_name])->first();
                    if($values){
                        $customs_values[$values->field_name]=$values->field_value;
                    }
                }
              
            }
        }
        return view('admin.data.form',compact('editData','category_id','defaults','customs','defaults_values','customs_values'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //所有参数
        $requestAll=$request->all();

        // dd($requestAll);
        $updateData=$request->only(['author','sort','is_top','is_recommend','is_release']);

        //创建
        $data=Data::find($id)->update($updateData);
                                                                            
        //遍历更新默认字段
        foreach ($requestAll as $key => $value) {
            if(strpos($key,'default_')!==false){
                $key=str_replace('default_','',$key);
                //更新当前默认字段
                $query=DB::table('default_values')
                ->where(['data_id'=>$id,'field_name'=>$key]);

                $is_has=$query->exists();
                //不存在则创建
                if($is_has){
                    $query->update(['field_value'=>$value]);
                }else{
                    DB::table('default_values')->insert([
                        'field_name'=>$key,
                        'field_value'=>$value,
                        'data_id'=>$id
                    ]);
                }
            }
        }

        //遍历更新自定义字段
        foreach ($requestAll as $key => $value) {
            if(strpos($key,'custom_')!==false){
                $key=str_replace('custom_','',$key);
                 //更新当前自定义字段
                $query=DB::table('custom_values')
                ->where(['data_id'=>$id,'field_name'=>$key]);
                $is_has=$query->exists();
                //不存在则创建
                if($is_has){
                    $query->update(['field_value'=>$value]);
                }else{
                    DB::table('custom_values')->insert([
                        'field_name'=>$key,
                        'field_value'=>$value,
                        'data_id'=>$id
                    ]);
                }
            }
        }

        return json(200,'修改成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $res=Data::find($id)->delete();
        if($res) return json(200,'删除成功');
        return json(105,'删除失败');
    }
}
